import store from '@/store'
import AUTH from '@/utils/auth'
import html2canvas from 'html2canvas'
import config from '@/config'
import { hasMiniMap } from '@/utils/menu'
import {
  isSceneActive,
  visiblePcAutoSwitch
} from '@/utils/krpano'
import {
  formatUrl,
  playSceneOrBgMusic,
  replaySceneOrBgMusic,
  pauseMenuOrPointAudio,
} from '@/utils/audio'
import { isPc } from '@/utils'

let navGuideObj = {
  index: 0,
  playing: false,
  timer: null
}

export const playNavGuide = () => {
  const navGuideList = store.getters.navGuideData
  let curScene = navGuideList[navGuideObj.index]
  let curSceneId = $VM.$krp.getSceneId()
  let PX = $VM.$krp.getSceneData("config.limitfov")

  // 如果陀螺仪是打开的会影响一键导览，需要先关闭
  if($VM.$krp.getGyroStatus()) {
    $VM.$krp.toggleGyro()
  }

  navGuideObj.index++
  if(!navGuideObj.playing) {
    $VM.$vgo.tip('一键导览开启', 'success')
  }
  navGuideObj.playing = true

  // 判断是否当前场景，如果不是则切换场景
  if (curScene.scene_id != curSceneId) {
    // console.log('qiehuan')
    $VM.$vgo.emit('sync:scene', curScene.scene_id)
  }

  $VM.$krp.callScene(
    `lookto(${curScene.ath},${curScene.atv},${PX},
    tween(easeInOutQuad,${parseInt(curScene.movetime)}),
    true,true,js(lookcallback()));`)

  // 如果是一键导览的话，并且有过场音乐
  if(curScene.music_url) {
    let musicurl = formatUrl(curScene.music_url)
    playSceneOrBgMusic(musicurl)

    // 过场音乐播放结束
    setTimeout(() => {
      pauseMenuOrPointAudio()
    }, curScene.movetime * 1000)
  }

  if(curScene.pic_url) {
    let navPic = formatUrl(curScene.pic_url)
    $VM.$vgo.emit('iframe:image', navPic)
  }

  clearTimeout(navGuideObj.timer)
  navGuideObj.timer = setTimeout(() => {
    if(navGuideObj.index >= navGuideList.length) {
      clearTimeout(navGuideObj.timer)

      navGuideObj.playing = false
      navGuideObj.index = 0

      // 重新播放场景或背景音乐
      replaySceneOrBgMusic()

      // 切换图标状态
      config.toolsBarMenu.map(item => {
        if(item.title === 'navguide') {
          item.isActive = false
        }
      })

      $VM.$vgo.emit('navigate:close')
      // 如果有过场图片则关闭
      $VM.$vgo.emit('iframe:image-close')
      $VM.$vgo.tip('一键导航结束', 'success')
    }
    else {
      if(navGuideObj.playing) {
        $VM.$vgo.emit('iframe:image-close')
        playNavGuide()
        $VM.$krp.stopTurn()
        clearAutoSwitch()
      }
    }
  }, curScene.movetime * 1000) // curScene.movetime
}

export const stopNavGuide = () => {
  clearTimeout(navGuideObj.timer)
  navGuideObj.playing = false
  navGuideObj.index = 0
  replaySceneOrBgMusic()
  restartAutoSwitch()

  $VM.$krp.autoTurn()
  $VM.$vgo.tip('一键导览关闭', 'success')
}

export const getSceneStatus = () => {
  // 第三套皮肤的场景一直隐藏状态
  // let themeId = store.getters.themeId
  // if(isMobile() && themeId && themeId == 2) {
  //   return false
  // }
  return isSceneActive()
}

export const handleSceneWidth = (sceneWidth, groupWidth) => {
  let sceneArr = store.getters.sceneList
  let groupArr = store.getters.sceneGroup
  let widthObj = {
    sw: 0,
    gw: 0
  }

  for(let i = 0, len = sceneArr.length; i < len; i++) {
    widthObj.sw += sceneWidth
  }
  for(let j = 0, len = groupArr.length; j < len; j++) {
    widthObj.gw += groupWidth
  }

  return widthObj
}
// 获取分组数据
export const handleSceneGroup = (groupId) => {
  const sceneGroup = store.getters.sceneGroup

  sceneGroup.map((item, idx) => {
    if(item.groupid == groupId) {
      store.dispatch('getCurSceneList', {data: item.scenelist, groupId: groupId})
      return idx
    }
  })
}

export const handleSceneItem = (item, groupId) => {
  setTimeout(() => {
    handleSwitchScene(item, groupId)
  }, 100)
}

export const handleSwitchScene = (item, groupId) => {
  // 要切换的场景不在当前显示分组, 更新数据
  if(groupId && groupId != store.getters.sceneGroupId) {
    handleSceneGroup(groupId)
  }

  let hotspots = store.getters.hotspots[item.scene_id]
  if(hotspots) {
    let max = hotspots.hotspotlist.length
    for(let i = 0; i < max; i++) {
      if(hotspots.hotspotlist[i].type_id == 15) {
        $VM.$vgo.emit('noticetip:show', {title: '欢迎参与找红包', desc: '场景内有大量现金红包随机散落在场景内，赶紧去找，晚了就没有啦！'})
        break
      }
    }
  }

  // 付费场景
  if(item.isLock == 1) {
    if(AUTH.checkLogin()) {
      // 去付费
      $VM.$vgo.tip('去付费', 'info')
      setTimeout(() => {
        if(!isPc()) {
          $VM.$router.push(`/panoview/${store.getters.panoId}/scenepay?id=${item.scene_id}`)
        } else {
          $VM.$vgo.emit('scenepay:show', item)
        }
      }, 1000)
    }
    return
  }

  let musicUrl = ''
  // 是否有场景音乐
  if(item.background_music_url) {
    musicUrl = item.full_background_music_url
  }
  // 存储当前场景音乐
  store.dispatch('getCurSceneMusic', musicUrl)
  playSceneOrBgMusic(musicUrl|| '')

  // 切换场景
  // $VM.$router.replace({
  //   name: $VM.$route.name, 
  //   query: Object.assign({},$VM.$route.query,{scene_id: item.scene_id}),
  //   params: $VM.$route.params
  // })
  $VM.$krp.switchEffect(item.scene_id)

  const themeType = store.getters.panoInfo.templatetype
  // 是否有小地图
  const miniMap = hasMiniMap(item.scene_id)
  // 新模板不用弹出小地图，因为小地图在屏幕中间显示，影响美观
  if(themeType !== 4) {
    let data = hasMiniMap(item.scene_id)
    $VM.$vgo.emit('show:minimap-icon', miniMap)
    $VM.$vgo.emit('update:minimap', data)
  } else {
    $VM.$vgo.emit('toggle:minimap-icon', miniMap ? true : false)
  }
}

let autoSwitchTimer // 自动切换定时器
let autoSIndex = 0
let autoGIndex = 0

// 自动切换场景
export const autoSwitchScene = (sIdx, gIdx, isClear) => {
  // 航拍模板不自动切换场景
  // if ($VM.$route.name === 'AerialPhotography') {return}
  // 景点模板不自动切换场景
  if (store.getters.panoInfo && (store.getters.panoInfo.templatetype == 11 || store.getters.panoInfo.templatetype == 12)) {
    return
  }

  if(visiblePcAutoSwitch()) {
    let panoInfo = store.getters.panoInfo
    let sceneGroup = store.getters.sceneGroup
    clearInterval(autoSwitchTimer)

    // 用户手动点击时，记录场景与分组下标
    autoSIndex = sIdx
    autoGIndex = gIdx

    // 如果是付费场景，获取不到下标的情况
    if(!sIdx || !gIdx) {
      sIdx = autoSIndex
      gIdx = autoGIndex
    }

    if(isClear) {
      clearInterval(autoSwitchTimer)
      autoSwitchTimer = null
    } else {
      autoSwitchTimer = setInterval(() => {
        sIdx++
        // 如果分组只有1个场景
        if(store.getters.sceneList.length == 1 && gIdx == sceneGroup.length - 1) {
          sIdx = 0
          gIdx = 0
        } else {
          if(sIdx >= store.getters.sceneList.length) {
            gIdx++
            if(gIdx >= sceneGroup.length) {
              gIdx = 0
            }
            sIdx = 0
          }
        }
        if(gIdx == sceneGroup.length) {
          gIdx = 0
        }

        autoSIndex = sIdx
        autoGIndex = gIdx

        handleSceneGroup(sceneGroup[gIdx].groupid)
        $VM.$vgo.emit('sync:scene', store.getters.sceneList[sIdx].scene_id, false)
      }, panoInfo.autoswitchtime * 1000) // panoInfo.autoswitchtime
    }
  }
}

// 清除自动切换场景
export const clearAutoSwitch = () => {
  autoSwitchScene(autoSIndex, autoGIndex, true)
}

// 重置自动切换状态
export const restartAutoSwitch = () => {
  autoSwitchScene(autoSIndex, autoGIndex, false)
}

// 长按截屏
let timeOutNumb = 0
export const handleScreenShotsDown = (e) => {
  e.preventDefault()
  $VM.$vgo.emit('canvas:show')
  setTimeout(handleScreenshots, 200)
  // if(e.touches && e.touches.length >= 2) return
  // timeOutNumb = setTimeout(logPress, 800)
}

export const handleScreenShotsMove = () => {
  clearTimeout(timeOutNumb)
  timeOutNumb = 0
}

export const handleScreenShotsEnd = () => {
  clearTimeout(timeOutNumb)
  if(timeOutNumb != 0) {}
  return false
}

export const logPress = () => {
  timeOutNumb = 0
  $VM.$vgo.emit('canvas:show')
  setTimeout(handleScreenshots, 200)
}

// 截屏处理
const handleScreenshots = function() {
  let cvs = document.querySelector('#krpanoSWFObject canvas')
  let cvsInner = document.querySelector('#canvasWrap #canvas-inner')
  html2canvas(cvs).then(function(canvas) {
    cvsInner.appendChild(canvas)
  })
}
 